package org.pearl.springboot.minio.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.pearl.springboot.minio.pojo.query.User;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by TD on 2021/9/14
 */
public class MvcPermissionInterceptor implements HandlerInterceptor {

    /**
     * 前置处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入MvcPermissionInterceptor");
        // 可以通过handler获取执行方法的相关信息, 方法名，注解等。
        // 1. 放行路径，直接放行，或者在注册时使用excludePathPatterns排除
        String requestURI = request.getRequestURI();
        if ("/test".equals(requestURI)) {
            System.out.println(requestURI + "放行！！！");
            return true;
        }
        Map<String, Object> result = new HashMap<>();
        // 2. 判断用户是有已登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            printMsg(result, response, HttpStatus.UNAUTHORIZED.value(), 401, "未登录！！！");
            return false;

        }
        // 3. 检查用户权限
        String permissionCode = user.getPermissionCode();
        if (!"add:user".equals(permissionCode)) {
            printMsg(result, response, HttpStatus.FORBIDDEN.value(), 403, "没权限");
            return false;
        }
        System.out.println("已登录，并拥有权限");
        return true;
    }

    /**
     * 响应错误信息
     */
    private void printMsg(Map<String, Object> result, HttpServletResponse response, int statusCode, int code, String msg) throws IOException {
        response.setStatus(statusCode);
        response.setContentType("application/json; charset=UTF-8");
        result.put("code", code);
        result.put("msg", msg);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getOutputStream(), result);
        response.setHeader("Cache-Control", "No-Cache");
        response.flushBuffer();
    }

    /**
     * 后置处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入MvcPermissionInterceptor postHandle");
    }

    /**
     * 完成处理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("进入MvcPermissionInterceptor afterCompletion");
    }
}
